/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


var counter = 0
function assert(result) {
    if (result != true) {
        throw new Error("Failed assertion №" + counter)
    }
    counter += 1
}

function fillMapWithRefs(weakMap, strongMap, count) {
    for (let i = 0; i < count; ++i) {
        let obj = { field: i }
        weakMap.set(obj, i)
        strongMap.set(obj, i)
    }
}

function validateMap(weakMap) {
    let obj = {testObject : 42}
    weakMap.set(obj, "value")
    if (!weakMap.has(obj)) {
        return false
    }
    if (weakMap.get(obj) != "value") {
        return false
    }
    weakMap.delete(obj)
    return !weakMap.has(obj)
}

function fillSetWithRefs(weakSet, strongSet, count) {
    for (let i = 0; i < count; ++i) {
        let obj = { field: i }
        weakSet.add(obj)
        strongSet.add(obj)
    }
}

function validateSet(weakSet) {
    let obj = {testObject : 42}
    weakSet.add(obj, "value")
    if (!weakSet.has(obj)) {
        return false
    }
    weakSet.delete(obj)
    return !weakSet.has(obj)
}

let weakMap = new WeakMap();
let strongMap = new Map()
fillMapWithRefs(weakMap, strongMap, 20)
assert(validateMap(weakMap))
assert(getContainerSize(weakMap) == 20)

collectGarbage()
assert(getContainerSize(weakMap) == 20)

strongMap.clear()
collectGarbage()
assert(getContainerSize(weakMap) == 0)
assert(validateMap(weakMap))

let weakSet = new WeakSet()
let strongSet = new Set()
fillSetWithRefs(weakSet, strongSet, 1)
assert(getContainerSize(weakSet) == 1)
strongSet.clear()
collectGarbage()
assert(getContainerSize(weakSet) == 0)
assert(validateSet(weakSet))